package com.dream.wukong.configcenter.client.remote.http;

import com.dream.wukong.configcenter.client.core.InitConfig;
import com.dream.wukong.configcenter.client.core.util.ConfigConstant;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;

/**
* 描  述: rest 风格配置中心资源获取的初始化服务类
* 创建时间: 2018/5/23
*/
public class HttpInitialize  {

    private static Logger logger = Logger.getLogger(HttpInitialize.class);

    private InitConfig initConfig;

    private volatile boolean inited = false;

    public HttpInitialize(InitConfig initConfig) {
        this.initConfig = initConfig;
        modifyConfigStatusByReflect();
        initConfigSource();
    }

    public static HttpInitialize getInstance() {
        return HttpInitializeHolder.INSTANCE;
    }

    ////////防止客户端错误的配置 对archaius相关的配置信息进行修改
    private void modifyConfigStatusByReflect() {
        logger.debug("--------检查配置加载状态--------");
        try {
            ConfigurationManager confMan = new ConfigurationManager();
            Class confManB = confMan.getClass();
            Field[] fs = confManB.getDeclaredFields();
            for(Field f:fs){
                f.setAccessible(true);
                Object val = f.get(confMan);
                if ("customConfigurationInstalled".equals(f.getName())) {
                    logger.debug("当前开关状态：" + f.getName() + " = " + val);
                    f.set(confMan, false);
                    val = f.get(confMan);
                    logger.debug("关闭后开关状态：" + f.getName() + " = " + val);
                }
            }
            DynamicPropertyFactory dy = DynamicPropertyFactory.getInstance();
            Class dyB = dy.getClass();
            Field[] dyfs = dyB.getDeclaredFields();
            for (Field dyf : dyfs) {
                dyf.setAccessible(true);
                Object val = dyf.get(dy);
                if ("config".equals(dyf.getName())) {
                    logger.debug("当前配置实例：" + dyf.getName() + " = " + val);
                    dyf.set(dy, null);
                    val = dyf.get(dy);
                    logger.debug("销毁后配置实例：" + dyf.getName() + " = " + val);
                }
            }
        } catch (Exception e) {
            logger.error("通过反射修改配置加载状态异常：" + e.getLocalizedMessage(), e);
        }
    }


    /***
    * 描  述:  初始化方法
    * 参  数:
    * 返回值: void
    * 创建时间: 2018/5/23
    */
    private void initConfigSource() {
        long begin = System.currentTimeMillis();
        logger.info("==========初始化配置中心开始==========");
        String initServiceName = initConfig.getServiceName();
        String initConfigIp = initConfig.getConfigIp();
        String initConfigPort = initConfig.getConfigPort();
        logger.info("检测环境变量：serviceName=" + initConfig.getServiceName() + ", configIp="
                + initConfig.getConfigIp() + ", configPort=" + initConfig.getConfigPort());
        if (StringUtils.isBlank(initServiceName)) {
            initServiceName = ConfigConstant.DEFAULT_SERVICE_NAME;
        }
        if (StringUtils.isBlank(initConfigIp)) {
            initConfigIp = ConfigConstant.DEFAULT_CONFIG_IP;
        }
        if (StringUtils.isBlank(initConfigPort)) {
            initConfigPort = ConfigConstant.DEFAULT_CONFIG_PORT;
        }
        logger.info("初始化环境变量：serviceName=" + initServiceName + ", configIp="
                + initConfigIp + ", configPort=" + initConfigPort);

        int initialDelayMillis = initConfig.getInitialDelayMillis();
        int delayMillis = initConfig.getDelayMillis();
        boolean ignoreDeletesFromSource = initConfig.isIgnoreDeletesFromSource();
        logger.info("初始化资源调度规则：initialDelayMillis=" + initialDelayMillis
                + "ms, delayMillis=" + delayMillis
                + "ms, ignoreDeletesFromSource=" + ignoreDeletesFromSource);
        String defaultConfigDirectoryUrl = "";
        String serviceConfigDirectoryUrl = "";
        if (StringUtils.isBlank(initConfigPort) || StringUtils.equals(initConfigPort,"80")) {
            defaultConfigDirectoryUrl = ConfigConstant.HTTP_PROTOCOL + initConfigIp
                    + ConfigConstant.DEFAULT_CONFIG;
            serviceConfigDirectoryUrl = ConfigConstant.HTTP_PROTOCOL + initConfigIp + ConfigConstant.CONFIG
                    + initServiceName + ConfigConstant.SLASH;
        } else {
            defaultConfigDirectoryUrl = ConfigConstant.HTTP_PROTOCOL  + initConfigIp + ConfigConstant.COLON
                    + initConfigPort + ConfigConstant.DEFAULT_CONFIG;
            serviceConfigDirectoryUrl = ConfigConstant.HTTP_PROTOCOL  + initConfigIp + ConfigConstant.COLON
                    + initConfigPort + ConfigConstant.CONFIG + initServiceName + ConfigConstant.SLASH;
        }
        /////remote server 获取配置信息
        HttpPullConfigScheduler.loadConfigSource(initialDelayMillis,
                delayMillis, ignoreDeletesFromSource,
                defaultConfigDirectoryUrl, serviceConfigDirectoryUrl);
        logger.info("==========初始化配置中心结束==========总耗时="
                + (System.currentTimeMillis() - begin) + "ms");
    }


    protected Object readResolve() {
        return HttpInitializeHolder.INSTANCE;
    }

    private static final class HttpInitializeHolder {
        private static final HttpInitialize INSTANCE = new HttpInitialize(InitConfig.getInstance());
    }
}
